package org.beetl.json.node;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import org.beetl.json.ActionReturn;
import org.beetl.json.DirectOutputValue;
import org.beetl.json.JsonTool;
import org.beetl.json.JsonWriter;
import org.beetl.json.OutputNode;
import org.beetl.json.Policy;
import org.beetl.json.action.IValueAction;

class NodeUtil {
	public static void writeUnkonw(OutputNode node,Object o,JsonWriter w, TreeSet<IValueAction>  valueActions) throws IOException{
		if(valueActions.size()!=0){			
			for(IValueAction valueAction:valueActions){
				ActionReturn ar = valueAction.doit(o, node);	
				o = ar.value;			
				if(!ar.process){
					break ;
				}
			}								
		}		
		
		if(o instanceof Iterable){
			Iterator it = ((Iterable)o).iterator();
				writeIterator(node,it,w);
		}else if( o instanceof Map){
			writeMap(node,(Map)o,w);
		}else if (o instanceof Enumeration){
			List list = Collections.list((Enumeration)o);
			writeIterator(node,list.iterator(),w);
		}else{
			Class cls = o.getClass();
			if(cls==DirectOutputValue.class){
				w.write((DirectOutputValue)o);
			}else if( cls.isArray()){
				List list = Arrays.asList((Object[])o);
				writeIterator(node,list.iterator(),w);
			}else if(cls.getPackage().getName().startsWith("java")){
				w.write(o);
			} else{
				JsonTool.serializeJW(w,o);
			}
				
				
			
		}
	}
	
	public  static void writeMap(OutputNode node,Map map,JsonWriter w) throws IOException{
		
		Iterator<Map.Entry> it = map.entrySet().iterator();
		if(!it.hasNext()){
			w.write("{}");
			return ;
		}
		w.writeScopeChar('{');
		while(true){
			Map.Entry item = it.next();
			w.write(item.getKey());
			w.write(':');			
			JsonTool.serializeJW(w,item.getValue());
			if(!it.hasNext()){
				w.writeScopeChar('}');
				return ;
			}
			
			w.writeComma();
			
		}		
	}
	
	public static void writeIterator(OutputNode node,Iterator it,JsonWriter w) throws IOException{
	
		if(!it.hasNext()){
			w.write("[]");
			return ;
		}
		w.writeScopeChar('[');
		while(true){
			Object item = it.next();
			if(item==null){
				w.write("null");
			}else{				
				JsonTool.serializeJW(w,item);
			}			
			if(!it.hasNext()){
				w.writeScopeChar(']');
				return ;
			}
			
			w.writeComma();
			
		}		
	}
}
